package com.zjw.socket.demo.starter.messageService.service.impl;


import com.zjw.socket.demo.starter.annotation.core.Bean;
import com.zjw.socket.demo.starter.messageService.service.IMessageDataBase;
import com.zjw.socket.demo.starter.messageService.Message;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 内存的直接存储
 */
@Bean(name = "MemoryMessageDataBase")
public class MemoryMessageDataBase implements IMessageDataBase {

  private final Map<Long, List<Message>> store = new ConcurrentHashMap<>();

  @Override
  public void insertMessageList(Message message) {
    List<Message> messages = store.computeIfAbsent(message.getToId(), it -> new ArrayList<>());
    messages.add(message);
  }

  @Override
  public List<Message> getMessageList(long userId) {
    return store.get(userId);
  }

  @Override
  public List<Message> removeMessageList(long userId) {
    return store.remove(userId);
  }

  @Override
  public void removeMessageBy(long userId, long fromId, int type) {
    List<Message> messageList = getMessageList(userId);
    if (messageList != null) {
      messageList.removeIf(next -> next.getFromId() == fromId && next.getType() == type);
    }
  }
}
